using Game.UI;
using UnityEngine;

namespace Game {
	public class FreeMovement : MonoBehaviour {
		public float MoveSpeed = 5f;
		public float SprintMultiplier = 2f;
		public float FreeLookSensitivity = 3f;

		private bool _looking = false;

		void Update() {
			var ui = UIHolder.Instance;
			if ( ui.HasFocus ) {
				StopLooking();
				return;
			}
			var h = Input.GetAxis("Horizontal");
			var v = Input.GetAxis("Vertical");
			var fastMode = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
			var moveVector = transform.TransformDirection(Vector3.forward) * Time.deltaTime * v * MoveSpeed + transform.TransformDirection(Vector3.right) * Time.deltaTime * h * MoveSpeed;
			if ( fastMode ) {
				moveVector *= SprintMultiplier;
			}
			transform.position += moveVector;

			if ( _looking ) {
				float newRotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * FreeLookSensitivity;
				float newRotationY = transform.localEulerAngles.x - Input.GetAxis("Mouse Y") * FreeLookSensitivity;
				transform.localEulerAngles = new Vector3(newRotationY, newRotationX, 0f);
			}

			if ( Input.GetKeyDown(KeyCode.Mouse1) ) {
				StartLooking();
			} else if ( Input.GetKeyUp(KeyCode.Mouse1) ) {
				StopLooking();
			}
		}

		void OnDisable() {
			StopLooking();
		}

		public void StartLooking() {
			_looking = true;
			Cursor.visible = false;
			Cursor.lockState = CursorLockMode.Locked;
		}

		public void StopLooking() {
			_looking = false;
			Cursor.visible = true;
			Cursor.lockState = CursorLockMode.None;
		}
	}
}

